﻿CREATE PROCEDURE [dbo].[proc_ContactPerson_Delete]
	(
		@PersonId uniqueidentifier
	)
AS
	begin
		Declare @IsMain bit,@CustomerId uniqueidentifier
		Select @IsMain=IsMain,@CustomerId=CustomerId From ContactPerson Where PersonId=@PersonId
		if(@IsMain=0)
			begin
				Delete From ContactPerson Where PersonId=@PersonId 
			end

--重新获取联系人和电话
declare @p_name nvarchar(50),@p_tel varchar(50)
Select Top 1 @p_name=ZName,@p_tel=Tel From(
Select Mobile As Tel,ZName,IsMain,PersonTypeId,'A' as sort
From ContactPerson
Where CustomerId=@CustomerId
And Mobile<>'' And (Mobile Is Not Null)
Union All
Select OfficeTel As Tel,ZName,IsMain,PersonTypeId,'B' as sort
From ContactPerson
Where CustomerId=@CustomerId
And OfficeTel<>'' And (OfficeTel Is Not Null)
Union All
Select HomeTel As Tel,ZName,IsMain,PersonTypeId,'C' as sort
From ContactPerson
Where CustomerId=@CustomerId
And HomeTel<>'' And (HomeTel Is Not Null)
) a Order By IsMain Desc,PersonTypeId,sort

--更新成单
	Update [Order] Set CusPerson=@p_name,CusPersonTel=@p_tel Where CusId=@CustomerId
	end
	RETURN


